package com.bolt.support.dynamic.datasource.autoconfigure;


import com.alibaba.druid.pool.DruidDataSource;
import com.bolt.support.dynamic.datasource.creator.DataSourceCreator;
import com.bolt.support.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.bolt.support.dynamic.datasource.creator.DruidDataSourceCreator;
import com.bolt.support.dynamic.datasource.creator.JndiDataSourceCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;

import java.util.List;


@Configuration
@ConditionalOnProperty(prefix = DynamicDataSourceProperties.PREFIX, name = "enabled", havingValue = "true")
public class DynamicDataSourceCreatorAutoConfiguration {
    public static final int JNDI_ORDER = 1000;
    public static final int DRUID_ORDER = 2000;

    @Primary
    @Bean
    @ConditionalOnMissingBean
    public DefaultDataSourceCreator dataSourceCreator(List<DataSourceCreator> dataSourceCreators) {
        DefaultDataSourceCreator defaultDataSourceCreator = new DefaultDataSourceCreator(dataSourceCreators);
         return defaultDataSourceCreator;
    }


    @Bean
    @Order(JNDI_ORDER)
    public JndiDataSourceCreator jndiDataSourceCreator() {
        return new JndiDataSourceCreator();
    }

    /**
     * 存在Druid数据源时, 加入创建器
     */
    @Bean
    @Order(DRUID_ORDER)
    @ConditionalOnClass(DruidDataSource.class)
    public DruidDataSourceCreator druidDataSourceCreator() {
        return new DruidDataSourceCreator();
    }

}
